<template>
  <div class="role">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色类别 -->
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbom', i1 === 0 ? 'bdtop':'','vcenter' ]"
            >
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '':'bdtop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      :class="[i3 === 0 ? '': 'bdtop']"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetDiolog(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 设置权限对话框 -->
    <el-dialog title="提示" :visible.sync="setdialogVisible"
    @close="beforeClose" width="50%" >
      <el-tree :data="powerList" :props="roleProps" ref="treeRef"
      :default-checked-keys="defKeys"
      node-key="id"
      show-checkbox  default-expand-all
     ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      setdialogVisible: false,
      powerList: [],
      roleProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      checkList: [],
      roleId: ''

    }
  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$axios.get('roles')
      this.rolesList = res.data
    },
    async removeRightById (role, id) {
      console.log(id)
      console.log(role)
      // 弹框提示用户是否删除
      const res = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res === 'cancel') {
        this.$message.info('取消了删除')
      } else {
        const { data: res1 } = await this.$axios.delete(
          `roles/${role.id}/rights/${id}`
        )
        if (res1.meta.status !== 200) {
          this.$message.error('删除角色权限失败')
        } else {
          this.$message.success('删除成功')
          role.children = res1.data
        }
      }
    },
    // 点击分配权限按钮，弹出对话框
    async  showSetDiolog (role) {
      // 获取权限列表
      this.roleId = role.id
      const { data: res } = await this.$axios.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.powerList = res.data
      this.getLeafKeys(role, this.defKeys)

      this.setdialogVisible = true
    },
    // 通过递归获取三级节点的选中id
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 弹框关闭前
    beforeClose () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$$message.error('修改权限失败')
      }
      this.$message.success('修改权限成功')
      this.getRolesList()

      this.setdialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
